package com.xoa.service.hr.impl;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;

import com.xoa.dao.hr.HrStaffEntryMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.department.Department;
import com.xoa.model.hr.HrStaffEntry;
import com.xoa.model.hr.HrStaffInfo;
import com.xoa.model.users.Users;
import com.xoa.service.hr.IntroductionService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IntroductionServiceImpl implements IntroductionService {
    @Resource
    private HrStaffEntryMapper introduceMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private SysCodeMapper sysCodeMapper;

    @Override
    public ToJson<HrStaffInfo> introductionInfo(PageParams pageParams, HrStaffEntry hrStaffEntry, HttpServletRequest request, HttpServletResponse response) {
        ToJson json = new ToJson(1, "暂无数据");
        Map<String, Object> map = new HashMap<String, Object>();
        String type = request.getParameter("type");
        try {
            PageParams pageParam = new PageParams();
            pageParam.setUseFlag(true);
            pageParam.setPageSize(pageParams.getPageSize());
            pageParam.setPage(pageParams.getPage());
            map.put("page", pageParam);
            map.put("staffName",hrStaffEntry.getStaffName());
            map.put("auditState",hrStaffEntry.getAuditState());
            if(!StringUtils.checkNull(type)&&"export".equals(type)){
                map.remove("page");
            }
        } catch (Exception e) {
            json.setFlag(1);
        }
        try {
            //获取当前登录人
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            String strStatus = null;
            boolean isass = true;
            // map.put("leavePerson",leavePerson);
            Department department = new Department();
            List<Department> deptList = new ArrayList<>();
            if (!"admin".equals(users.getUserId())) {
                //审核状态
                switch (users.getUserPriv()) {
                    case 6:
                        //
                        department.setDeptId(users.getDeptId());
                        deptList.add(department);
                        getChildDept(deptList);
                        map.put("deptId", getChildDept(deptList).toArray());
                        map.put("uid",users.getUid());
                        break;
                    case 4:
                        //
                        department.setDeptId(users.getDeptId());
                        deptList.add(department);
                        getChildDept(deptList);
                        map.put("deptId", getChildDept(deptList).toArray());
                        break;
                    case 5:
                        //
                        department.setDeptId(users.getDeptId());
                        deptList.add(department);
                        getChildDept(deptList);
                        map.put("deptId", getChildDept(deptList).toArray());
                        break;
                   /* case 10:
                        //
                        strStatus = "4";
                        break;*/
                    case 2:
                        //
                        strStatus = "5";
                        break;
                    case 1:
                        strStatus = null;
                        break;
                }
            }

            if (isass){
                //分页拦截器不支持IN查询
                Integer countTo=null;
                if (!StringUtils.checkNull(strStatus)){
                    map.put("auditState",strStatus);
                }


                List<HrStaffEntry> list = introduceMapper.selectIntroductionInfo1(map);

                map.remove("page");
                countTo=introduceMapper.countIntroductionInfo(map);
                json.setTotleNum(countTo);
                for(HrStaffEntry listLimi : list){
                    //品类
                    //人事档案存储品类字段
                    String category = listLimi.getCategory();
                    //品类
                    SysCode categoryNew = sysCodeMapper.getSingleCode("CATEGORY", category);
                    if(categoryNew!=null){
                        listLimi.setCategoryName(categoryNew.getCodeName());
                        //品牌
                        //人事档案存储品类字段
                        String brand = listLimi.getBrand();
                        //父类
                        String codeNo = categoryNew.getCodeNo();
                        //品牌
                        SysCode brandNew = sysCodeMapper.getSingleCode(codeNo, brand);
                        if(brandNew!=null){
                            listLimi.setBrandName(brandNew.getCodeName());
                        }
                    }


                    //岗位
                    //人事档案存储品类字段
                    String workJob = listLimi.getWorkJob();
                    //岗位
                    SysCode workJobNew = sysCodeMapper.getSingleCode("jd_wordjob", workJob);
                    if(workJobNew!=null){
                        listLimi.setWorkJobName(workJobNew.getCodeName());
                    }
                }
                if(!StringUtils.checkNull(type)&&"export".equals(type)){
                    for (int i = 0; i < list.size(); i++) {
                        HrStaffEntry hrStaffEntry1 = list.get(i);
                        if(hrStaffEntry1.getDeptId()!=null){
                            Department deptById = departmentMapper.getDeptById(hrStaffEntry1.getDeptId());
                            if(deptById!=null){
                                hrStaffEntry1.setHomeAddress(deptById.getDeptName());
                            }else{
                                hrStaffEntry1.setHomeAddress("部门不存在");
                            }
                        }
                    }

                    HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("员工入职信息表", 7);

                    String[] secondTitles = {"部门","姓名","身份证号","手机号","岗位", "品类", "品牌", "入职京东时间", "电子邮箱","采销", "审核状态",};
                    HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                    String[] beanProperty = {"homeAddress","staffName","staffCardNo","staffPhone", "workJobName", "categoryName", "brandName", "datesEmployed", "staffEmail", "adoptPinName", "auditStateStr"};

                    HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, list, beanProperty);
                    ServletOutputStream out = response.getOutputStream();

                    String filename = "员工入职信息表.xls";
                    filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                    response.setContentType("application/vnd.ms-excel");
                    response.setHeader("content-disposition", "attachment;filename=" + filename);
                    workbook.write(out);
                    out.close();

                }
                json.setFlag(0);
                json.setMsg("查询成功");
                json.setObj(list);
                json.setObject(users);
                if (countTo==null){
                    //分页总数
                    PageParams pageParam=(PageParams) map.get("page");
                    json.setTotleNum(pageParam.getTotal());
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }

    @Override
    public ToJson<HrStaffInfo> introductionConditionQuery(String introductionPerson, String category, String quitTimePlanStart, String quitTimeFactEnd, String brand, String userName, Boolean useFlag, Integer pageSize, Integer page, HttpServletRequest request) {
        ToJson json = new ToJson(1, "服务异常");
        try {

            //分页
            PageParams pageParams = new PageParams();
            pageParams.setUseFlag(useFlag);
            pageParams.setPageSize(pageSize);
            pageParams.setPage(page);

            //把leavePerson和leaveDept后面的逗号去掉
            if (null != introductionPerson && introductionPerson.contains(",")) {
                String[] tempArray = introductionPerson.split(",");
                introductionPerson = tempArray[0];
            }

            //配置条件参数集合
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            parameterMap.put("introductionPerson", introductionPerson);
            if ("".equals(quitTimePlanStart)) {
                quitTimePlanStart = null;
            }
            if ("".equals(quitTimeFactEnd)) {
                quitTimeFactEnd = null;
            }
            parameterMap.put("quitTimePlanStart", quitTimePlanStart);
            parameterMap.put("quitTimePlanEnd", quitTimeFactEnd);
            parameterMap.put("page", pageParams);
            parameterMap.put("category", category);
            parameterMap.put("brand", brand);
            List<HrStaffEntry> InfoList = new ArrayList<HrStaffEntry>();

            // if(notNullOrEmpty(introductionPerson)||notNullOrEmpty(quitTimePlanStart)||notNullOrEmpty(quitTimeFactEnd)||notNullOrEmpty(userName)) {
            InfoList = introduceMapper.selectIntroductionInfo(parameterMap);
            //查询
            //  leaveInfoList =introduceMapper.selectByConditions(parameterMap);
            //}
            // handleHrStaffLeaveOutput(leaveInfoList);
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            json.setFlag(0);
            json.setMsg("查询成功");
            json.setObj(InfoList);
            json.setObject(users);
            json.setTotleNum(pageParams.getTotal());
            //   json.setTotleNum(introduceMapper.selectCountByConditions(parameterMap));
        } catch (Exception e) {
            json.setMsg("出现异常");
            json.setObject(e);
        }
        return json;
    }

    //判断对象是否为null或空字符串
    private static boolean notNullOrEmpty(Object object) {
        try {
            return null != object && !"".equals(object.toString().trim());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private List<String> getChildDept(List<Department> departs) throws Exception {
        List<String> deptIds = new ArrayList<>();
        for (Department d : departs) {
            deptIds.add(String.valueOf(d.getDeptId()));
            List<Department> chDept = departmentMapper.getChDept(d.getDeptId());
            if (chDept != null && chDept.size() > 0) {
                d.setChild(chDept);
                deptIds.addAll(getChildDept(chDept));
            }
        }
        return deptIds;
    }
}

